'use client';

import React, { useState, useEffect } from 'react';
import { MessageCircle, Settings, BarChart3 } from 'lucide-react';
import ChatWidget from '@/components/ChatWidget';
import { testApiClient } from '@/lib/testApi';

export default function HomePage() {
  const [chatflowId] = useState(process.env.NEXT_PUBLIC_CHATFLOW_ID || 'default-chatflow');
  const [userId, setUserId] = useState<string>('');

  // 在客户端挂载后生成用户 ID，避免水合错误
  useEffect(() => {
    // 尝试从 localStorage 获取已存在的用户 ID
    let existingUserId = localStorage.getItem('flowise-user-id');
    
    if (!existingUserId) {
      // 如果没有，生成新的用户 ID 并保存
      existingUserId = 'user-' + Math.random().toString(36).substr(2, 9);
      localStorage.setItem('flowise-user-id', existingUserId);
    }
    
    setUserId(existingUserId);
    
    // 在开发环境中运行 API 测试
    if (process.env.NODE_ENV === 'development') {
      console.log('开发环境：API 测试函数已加载，可在控制台运行 testApiClient()');
    }
  }, []);

  const handleTraceGenerated = (sessionId: string) => {
    console.log('新的执行追踪生成:', sessionId);
    // 这里可以添加通知逻辑，比如显示一个提示
  };

  return (
    <div className="min-h-screen bg-gray-50">
      {/* 导航栏 */}
      <nav className="bg-white shadow-sm border-b border-gray-200">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="flex justify-between h-16">
            <div className="flex items-center">
              <MessageCircle className="w-8 h-8 text-primary-600" />
              <h1 className="ml-2 text-xl font-semibold text-gray-900">
                PG Flowise - AI 对话系统
              </h1>
            </div>
            
            <div className="flex items-center space-x-4">
              <button
                onClick={() => window.open('/admin', '_blank')}
                className="flex items-center space-x-2 px-3 py-2 text-sm text-gray-600 hover:text-gray-900 transition-colors"
              >
                <BarChart3 className="w-4 h-4" />
                <span>管理后台</span>
              </button>
              <button className="flex items-center space-x-2 px-3 py-2 text-sm text-gray-600 hover:text-gray-900 transition-colors">
                <Settings className="w-4 h-4" />
                <span>设置</span>
              </button>
            </div>
          </div>
        </div>
      </nav>

      {/* 主内容区域 */}
      <main className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
          {/* 聊天区域 */}
          <div className="lg:col-span-2">
            <div className="h-[600px]">
              {userId ? (
                <ChatWidget
                  chatflowId={chatflowId}
                  userId={userId}
                  onTraceGenerated={handleTraceGenerated}
                />
              ) : (
                <div className="flex items-center justify-center h-full bg-white rounded-lg shadow-sm border border-gray-200">
                  <div className="text-center">
                    <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary-600 mx-auto mb-4"></div>
                    <p className="text-gray-600">正在初始化用户会话...</p>
                  </div>
                </div>
              )}
            </div>
          </div>

          {/* 侧边栏信息 */}
          <div className="space-y-6">
            {/* 系统信息 */}
            <div className="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
              <h2 className="text-lg font-semibold text-gray-900 mb-4">系统信息</h2>
              <div className="space-y-3 text-sm">
                <div className="flex justify-between">
                  <span className="text-gray-600">用户 ID:</span>
                  <span className="font-mono text-gray-900">{userId || '加载中...'}</span>
                </div>
                <div className="flex justify-between">
                  <span className="text-gray-600">流程 ID:</span>
                  <span className="font-mono text-gray-900">{chatflowId}</span>
                </div>
                <div className="flex justify-between">
                  <span className="text-gray-600">状态:</span>
                  <span className="text-green-600">在线</span>
                </div>
              </div>
            </div>

            {/* 使用说明 */}
            <div className="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
              <h2 className="text-lg font-semibold text-gray-900 mb-4">使用说明</h2>
              <div className="space-y-3 text-sm text-gray-600">
                <div className="flex items-start space-x-2">
                  <div className="w-2 h-2 bg-primary-600 rounded-full mt-2 flex-shrink-0"></div>
                  <p>在下方输入框中输入您的问题，AI 助手会为您提供回答</p>
                </div>
                <div className="flex items-start space-x-2">
                  <div className="w-2 h-2 bg-primary-600 rounded-full mt-2 flex-shrink-0"></div>
                  <p>点击回答中的"查看思考过程"可以了解 AI 的推理步骤</p>
                </div>
                <div className="flex items-start space-x-2">
                  <div className="w-2 h-2 bg-primary-600 rounded-full mt-2 flex-shrink-0"></div>
                  <p>在管理后台可以查看详细的执行追踪和分析数据</p>
                </div>
              </div>
            </div>

            {/* 功能特性 */}
            <div className="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
              <h2 className="text-lg font-semibold text-gray-900 mb-4">功能特性</h2>
              <div className="grid grid-cols-2 gap-3 text-sm">
                <div className="text-center p-3 bg-blue-50 rounded-lg">
                  <div className="text-blue-600 font-medium">智能问答</div>
                  <div className="text-blue-500 text-xs mt-1">基于 Flowise</div>
                </div>
                <div className="text-center p-3 bg-green-50 rounded-lg">
                  <div className="text-green-600 font-medium">思考可视化</div>
                  <div className="text-green-500 text-xs mt-1">完整追踪</div>
                </div>
                <div className="text-center p-3 bg-purple-50 rounded-lg">
                  <div className="text-purple-600 font-medium">工具调用</div>
                  <div className="text-purple-500 text-xs mt-1">透明展示</div>
                </div>
                <div className="text-center p-3 bg-yellow-50 rounded-lg">
                  <div className="text-yellow-600 font-medium">文档检索</div>
                  <div className="text-yellow-500 text-xs mt-1">来源可查</div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </main>
    </div>
  );
}
